// 使用uni.request发起请求,封装成promise对象,提供get和post方法
import { BASE_URL } from '@/config';
import { httpCode } from './httpCode';
import tokenManage from './token';
const errorTips = (tip) => {
  uni.showToast({
    title: tip || '系统异常，请稍后再试',
    icon: 'none',
    duration: 2000,
  });
};
export const login = (data) => post('/api/login', data);
export const refreshToken = (data) => post('/api/user/refresh-token', data);
let refreshing = false;
let refreshQueue = [];

function handleRefreshToken() {
  return new Promise((resolve, reject) => {
    refreshToken().then((res) => {
      if (res.code === 200) {
        tokenManage.setToken(res.data.token);
        resolve();
      }
    });
  });
}

function handleLogin() {
  return new Promise((resolve, reject) => {
    login({ phone: 17608015960, pwd: '123' }).then((res) => {
      if (res.code === 200) {
        tokenManage.setToken(res.data.token);
        resolve();
      }
    });
  });
}
export const http = (url, data, method = 'GET', headers = {}) => {
  return new Promise((resolve, reject) => {
    // 发起请求
    uni.request({
      url: BASE_URL + url,
      data,
      method,
      header: {
        'content-type': 'application/json',
        Authorization: tokenManage.getToken() || '',
        ...headers,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          switch (res.data.code) {
            case httpCode.OK: {
              resolve(res.data);
              break;
            }
            case httpCode.INTERNAL_SERVER_ERROR:
            case httpCode.SERVICE_UNAVAILABLE:
            case httpCode.BUSINESS_ERROR:
            case httpCode.NOT_FOUND:
            case httpCode.FORBIDDEN:
            case httpCode.BAD_REQUEST: {
              errorTips(res.data.msg);
              break;
            }
            case httpCode.NEED_LOGIN: {
              handleLogin()
                .then(async() => {
                  // 登录后重新请求
                  const resAfter = await http(url, data, method, headers);
                  console.log('resAfter', resAfter);
                  resolve({ code: httpCode.OK, data: resAfter.data });
                })
                .catch(() => {
                  reject({ code: httpCode.NEED_LOGIN });
                });
              break;
            }
            case httpCode.NEED_REFRESH: {
              if (!refreshing) {
                refreshing = true;
                handleRefreshToken()
                  .then(() => {
                    refreshing = false;
                    refreshQueue.forEach((fn) => fn());
                    refreshQueue = [];
                    resolve({ code: httpCode.OK, data });
                  })
                  .catch(() => {
                    refreshing = false;
                    reject({ code: httpCode.NEED_LOGIN });
                  });
              } else {
                return new Promise((resolve) => {
                  refreshQueue.push(() => {
                    http(url, data, method, headers).then(resolve);
                  });
                });
              }
              break;
            }
            default: {
              break;
            }
          }

          if (res.data.code !== httpCode.OK) {
            return reject(res.data);
          } else {
            resolve(res.data);
          }
        }
      },
      fail: (err) => {
        // 请求失败
        reject(err);
      },
    });
  });
};
export const get = (url, data) => http(url, data, 'GET');
export const post = (url, data) => http(url, data, 'POST');
